import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import { Inject, Injectable, PLATFORM_ID } from '@angular/core';
import { Observable, throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class BaiduMapsService {
  private ak = 'tjdm4m7hWTjc82OAKSNzbpecHp7YLZiO';

  private baiduMapsScriptSrc = `https://api.map.baidu.com/api?v=1.0&type=webgl&ak=${this.ak}&callback=initializeMap`;

  constructor(@Inject(DOCUMENT) private document: Document, @Inject(PLATFORM_ID) private platformId: any) {}

  initBaiduMaps(baiduMapsScriptSrc?: string) {
    if (!isPlatformBrowser(this.platformId)) {
      return throwError(() => '请在浏览器中执行');
    }
    return new Observable(observer => {
      const baiduMapsScriptEl = this.document.createElement('script');
      baiduMapsScriptEl.src = baiduMapsScriptSrc || this.baiduMapsScriptSrc;
      this.document.head.appendChild(baiduMapsScriptEl);
      (window as any).initializeMap = () => {
        observer.next(true);
        observer.complete();
      };
    });
  }
}
